/* login.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"

int main() {
    sqlite3  *db  = NULL;
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    char     sql[500];
    char     *input;
    char     *req_method;
    int      rc;

    rc = sqlite3_open(PATH_DATABASE,&db);
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        printf("Content-type:text/html;charset=utf-8\n\n");
        printf("DB error.");
        return 0;

    } else {
        // get request parameter
        req_method = getenv("REQUEST_METHOD");
        input = getcgidata(stdin, req_method);

        PARAM username = getParam(input, "username");
        PARAM password = getParam(input, "password");

        sprintf(sql, "select * from [tb_user] where name = '%s' ", username.value);

        char *pwd = {0};

        rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            sqlite3_close(db);
            return 0;
        } if (*azResult != NULL) {
            int i, j;
            for(i=0; i<=nrow; i++) {
                if(i==0) continue;
                for(j=0; j<ncolumn; j++) {
                    if( strcmp(azResult[j], "pwd") == 0 ){
                         pwd = azResult[ (i*ncolumn) + j ];
                    }
                }
            }
        }
        if( pwd!=NULL ){
            if( strcmp(password.value, pwd)==0){
                // authencated request
                set_cookie(username.value, password.value);
            } else {
                printf("Content-type:text/html;charset=utf-8\n\n");
                printf("<meta http-equiv=\"Refresh\" content=\"0;URL=/index.html\">");
            }
        } else {
            printf("Content-type:text/html;charset=utf-8\n\n");
            printf("<meta http-equiv=\"Refresh\" content=\"0;URL=/index.html\">");
        }
    }

    sqlite3_close(db);
    return 0;
}
